package org.hard.netty.c1;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 黏包半包解析
 * @author: 王林博
 * @date: 2022年08月11日 16:13
 */
public class TestByteBufferExam {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("Hello\nI`m wang\nHe".getBytes(StandardCharsets.UTF_8));
        split(buffer);
        buffer.put("llo\n".getBytes(StandardCharsets.UTF_8));
        split(buffer);
    }

    private static void split(ByteBuffer source){
        source.flip(); // 读模式
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') { // 截取
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                target.flip();
                System.out.println((char) target.get());
                System.out.println((char) target.get(target.limit()-2));
            }
        }
        source.compact();// 写模式 ->最后未读的往前移动
    }
}
